package com.test.base.utils;

import com.alibaba.fastjson.JSONObject;
import com.test.base.vo.api.WxInfoResult;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Calendar;
import java.util.Date;

public class TokenUtil {
    /**
     * 密匙
     */
    private static final String SECRET = "SLDLKKDS323ssdd@#@@gf";

    public static String create(String subject, Date expDate) {
        return Jwts.builder()
                .setExpiration(expDate)
                .setSubject(subject)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    public static WxInfoResult pase(String subject) {
        String jsonString = null;
        try {
            jsonString = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(subject).getBody().getSubject();
            return JSONObject.parseObject(jsonString, WxInfoResult.class);
        } catch (ExpiredJwtException e) {
            return null;
        }
    }

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2016, 12, 1, 0, 0, 0);
        String pwd = Jwts.builder()
                .setExpiration(calendar.getTime())
                .setSubject("aaaa")
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        String jsonString = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(pwd).getBody().getSubject();
        System.out.printf(jsonString);
    }
}
